package com.example.competition_1.services;

import com.example.competition_1.models.entity.*;
import org.springframework.stereotype.Service;
import gaarason.database.contract.eloquent.RecordList;
import gaarason.database.contract.eloquent.Record;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AwardService {

    private final Work.Model workModel;
    private final WorkUser.Model workUserModel;
    private final Competitions.Model competitionsModel;

    private final AwardWorkCompetition.Model awardWorkCompetitionModel;

    private final Award.Model awardModel;

    public AwardService(Work.Model workModel, WorkUser.Model workUserModel, Competitions.Model competitionsModel, AwardWorkCompetition.Model awardWorkCompetitionModel, Award.Model awardModel) {
        this.workModel = workModel;
        this.workUserModel = workUserModel;
        this.competitionsModel = competitionsModel;
        this.awardWorkCompetitionModel = awardWorkCompetitionModel;
        this.awardModel = awardModel;
    }


    public boolean addAward(Award award, String competitionName, String workName) {
        try {
            // 设置创建时间
            award.setCreateat(LocalDateTime.now());

            // 生成唯一的 awardId
            award.setAwarid(IdGenerator.generateWorkId());

            // 插入数据到 Award 表
            awardModel.newQuery().insert(award);
            System.out.println("成功插入数据，ID: " + award.getAwarid());

            // 根据 competitionName 查询 competitionId
            String competitionId = null;
            RecordList<Competitions, ?> competitionRecords = competitionsModel.newQuery()
                    .where("name", competitionName)
                    .get();
            List<Competitions> competitions = competitionRecords.stream()
                    .map(Record::getEntity)
                    .collect(Collectors.toList());
            if (competitions.isEmpty()) {
                System.out.println("未找到对应的 competition 记录");
                return false;
            }
            competitionId = competitions.get(0).getId();

            // 根据 workName 查询 workId
            String workId = null;
            RecordList<Work, ?> workRecords = workModel.newQuery()
                    .where("workName", workName)
                    .get();
            List<Work> works = workRecords.stream()
                    .map(Record::getEntity)
                    .collect(Collectors.toList());
            if (works.isEmpty()) {
                System.out.println("未找到对应的 work 记录");
                return false;
            }
            workId = works.get(0).getWorkid();

            // 生成唯一的 id
            String id = IdGenerator.generateWorkId();

            // 创建 AwardWorkCompetition 对象
            AwardWorkCompetition awardWorkCompetition = new AwardWorkCompetition();
            awardWorkCompetition.setWorkid(workId);
            awardWorkCompetition.setCompetitionid(competitionId);
            awardWorkCompetition.setAwardid(award.getAwarid());
            awardWorkCompetition.setId(id);

            // 插入数据到 AwardWorkCompetition 表
            awardWorkCompetitionModel.newQuery().insert(awardWorkCompetition);
            System.out.println("成功插入数据到 award_work_competition 表，ID: " + id);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("插入数据时发生异常：" + e.getMessage());
            return false;
        }
    }
    public boolean updateAward(String awarId, Award updatedAward) {
        try {
            updatedAward.setUpdateat(LocalDateTime.now());

            updatedAward.setAwarid(awarId);

            int updatedCount = awardModel.newQuery()
                    .where("awarId", awarId)
                    .update(updatedAward);

            return updatedCount > 0;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("更新数据时发生异常：" + e.getMessage());
            return false;
        }
    }

    // 删除获奖信息
    public boolean deleteAward(String awarId) {
        try {
            // 通过 awardId 在 award_work_competition 表中查找 workId
            RecordList<AwardWorkCompetition, ?> awardWorkCompetitionRecords = awardWorkCompetitionModel.newQuery()
                    .where("awarId", awarId)
                    .get();
            List<AwardWorkCompetition> awardWorkCompetitions = awardWorkCompetitionRecords.stream()
                    .map(Record::getEntity)
                    .collect(Collectors.toList());

            if (awardWorkCompetitions.isEmpty()) {
                System.out.println("未找到对应的 award_work_competition 记录");
                return false;
            }

            String workId = awardWorkCompetitions.get(0).getWorkid();

            // 根据 workId 查找 work 表中的记录
            RecordList<Work, ?> workRecords = workModel.newQuery()
                    .where("workId", workId)
                    .get();
            List<Work> works = workRecords.stream()
                    .map(Record::getEntity)
                    .collect(Collectors.toList());

            if (works.isEmpty()) {
                System.out.println("未找到对应的 work 记录");
                return false;
            }

            Work work = works.get(0);
            // 将 work 记录的 status 字段修改为 2
            work.setStatus(2);
            workModel.newQuery().update(work);

            System.out.println("成功将 work 记录的 status 修改为 2，workId: " + workId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("修改 work 记录的 status 时发生异常：" + e.getMessage());
            return false;
        }
    }

    // 查看所有获奖记录
    public List<Map<String, Object>> getAllAwards() {
        System.out.println("开始执行 getAllAwards 方法");
        List<Map<String, Object>> resultList = new ArrayList<>();

        System.out.println("开始查询所有 Award 记录");
        // 查询所有 Award 记录
        RecordList<Award, ?> awardRecords = awardModel.newQuery().get();
        List<Award> awards = awardRecords.stream()
                .map(Record::getEntity)
                .collect(Collectors.toList());
        System.out.println("查询到的 Award 记录数量: " + awards.size());

        for (Award award : awards) {
            System.out.println("开始处理奖项，awardId: " + award.getAwarid());
            String awardId = award.getAwarid();

            System.out.println("开始查询与该奖项关联的作品列表...");
            List<String> workIds = awardWorkCompetitionModel.newQuery()
                    .where("awardId", awardId)
                    .select("workId")
                    .get()
                    .stream()
                    .map(Record::getEntity)
                    .map(AwardWorkCompetition::getWorkid)
                    .collect(Collectors.toList());
            System.out.println("查询到与该奖项关联的作品数量: " + workIds.size());

            for (String workId : workIds) {
                System.out.println("开始处理作品，workId: " + workId);

                System.out.println("开始查询该作品的详细信息...");
                List<Work> works = workModel.newQuery()
                        .where("workId", workId)
                        .get()
                        .stream()
                        .map(Record::getEntity)
                        .collect(Collectors.toList());
                System.out.println("查询到该作品的详细信息数量: " + works.size());

                for (Work work : works) {
                    String competitionId = work.getCompetitionid();

                    System.out.println("开始查询该作品对应的竞赛信息...");
                    List<Competitions> competitionList = competitionsModel.newQuery()
                            .where("id", competitionId)
                            .get()
                            .stream()
                            .map(Record::getEntity)
                            .collect(Collectors.toList());
                    System.out.println("查询到的竞赛信息数量: " + competitionList.size());

                    Competitions competition = null;
                    if (!competitionList.isEmpty()) {
                        competition = competitionList.get(0);
                    }

                    String competitionName = competition != null? competition.getName() : "";

                    System.out.println("开始查询该作品的参与者列表...");
                    List<WorkUser> workUsers = workUserModel.newQuery()
                            .where("workId", workId)
                            .get()
                            .stream()
                            .map(Record::getEntity)
                            .collect(Collectors.toList());
                    System.out.println("查询到该作品的参与者数量: " + workUsers.size());

                    Map<String, Object> combinedData = new HashMap<>();
                    // 平铺award表信息
                    combinedData.put("awardId", award.getAwarid());
                    combinedData.put("awardDescription", award.getDescription());
                    combinedData.put("awardPrize", award.getAwardprize());
                    combinedData.put("awardTime", award.getAwardtime());
                    combinedData.put("createAt", award.getCreateat());
                    combinedData.put("updateAt", award.getUpdateat());
                    // 平铺work表信息
                    combinedData.put("workId", work.getWorkid());
                    combinedData.put("workName", work.getWorkname());
                    combinedData.put("competitionId", work.getCompetitionid());
                    combinedData.put("status", work.getStatus());
                    combinedData.put("description", work.getDescription());
                    combinedData.put("category", work.getCategory());
                    combinedData.put("teachStack", work.getTeachstack());
                    combinedData.put("date", work.getDate());

                    combinedData.put("workUsers", workUsers);

                    combinedData.put("competitionName", competitionName);

                    resultList.add(combinedData);
                    System.out.println("作品 " + workId + " 处理完成");
                }
            }
            System.out.println("奖项 " + awardId + " 处理完成");
        }

        System.out.println("getAllAwards 方法执行完毕，最终结果数量: " + resultList.size());
        return resultList;
    }
}